// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
app = angular.module('starter', ['ionic', 'ionic-datepicker', 'angular-timeline', 'ionic-toast', 'ionic-timepicker', 'starter.controllers', 'starter.services', 'starter.filter', 'ngResource', 'ngCookies'])

.run(function($ionicPlatform, $state, $rootScope, $log, $ionicLoading, $ionicHistory, $cookieStore, $interval, $ionicScrollDelegate, Utils, ionicToast, VacationTypeService, UserService) {
  $interval(function() {
    UserService.noop()
  }, 10000)
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true)
      cordova.plugins.Keyboard.disableScroll(true)

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault()
    }

    // root下得工具包
    $rootScope.root = $rootScope

    $rootScope.showTabs = true
    $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
      var startState = ['tab.notifications', 'tab.vacations.list', 'tab.judge.list', 'tab.mine.dash']
      $rootScope.showTabs = _.includes(startState, toState.name)
    })

    $rootScope.scrollBottom = function(){
      $ionicScrollDelegate.scrollBottom(true)
    }

    $rootScope.goBack = function() {
      $ionicHistory.goBack()
    }

    $rootScope.isLogin = function() {
      return Utils.isLogin()
    }

    $rootScope.canJudge = function() {
      return Utils.canJudge()
    }

    $rootScope.canCalculate = function() {
      return Utils.canCalculate()
    }

    $rootScope.isStatistic = function() {
      return Utils.isStatistic()
    }

    $rootScope.isUserCanJudgeVacation = function(vacation) {
      return Utils.isUserCanJudgeVacation(vacation)
    }

    $rootScope.toast = function(message) {
      ionicToast.show(message, 'bottom', false, 2000)
    }

    $rootScope.loadCount = 0
    $rootScope.loading = function(isloading) {
      if (isloading) {
        $ionicLoading.show({
          template: '<ion-spinner icon="lines"></ion-spinner>'
        })
      } else {
        $ionicLoading.hide()
      }
    }

    $rootScope.user = Utils.getUser()

    // 获取类型
    if (!$rootScope.types) {
      // 设置全局类型
      VacationTypeService.query().$promise.then(function(res) {
        if (Utils.isResponseOk(res)) {
          $rootScope.types = res
        }
      })
    }

    $rootScope.findFirstType = function(id) {
      return angular.copy(_.find($rootScope.types, function(type) {
        return type.id == id
      }))
    }


    $rootScope.findSecondType = function(id1, id2) {
      console.log(id1 + '  ' + id2)
      var type1 = _.find($rootScope.types, function(type) {
        return type.id == id1
      })

      var type2 = angular.copy(_.find(type1.subTypes, function(type) {
        return type.id == id2
      }))
      // console.log(type2)
      return type2
    }

    // 根据类型字符串生成二级类型表
    $rootScope.generateSubTypes = function(id, str) {
      // console.log(id + '   ' + str)
      if (!str ||!id) return
      var temp = str.split(',')
      var list = []
      // console.log(temp)

      for (var i = 0; i < temp.length; i++) {
        var type2 = $rootScope.findSecondType(id, temp[i])
        // console.log(type2)
        list.push(type2)
        // console.log(list)

      }
      return list
    }

    $rootScope.$on('user:update', function () {
      UserService.get().$promise.then(function (res) {
        if(Utils.isResponseOk(res)){
          Utils.setUser(res)
          $rootScope.user = Utils.getUser()
        }
      })
    })
  })
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider, $httpProvider) {

  $ionicConfigProvider.tabs.position("bottom") //Places them at the bottom for all OS
  $ionicConfigProvider.tabs.style("standard") //Makes them all look the same across all OS
  $ionicConfigProvider.tabs.style("standard") //Makes them all look the same across all OS
  $ionicConfigProvider.navBar.alignTitle('center')
    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js

  $httpProvider.defaults.timeout = 10000
  $httpProvider.defaults.useXDomain = true
    // 保持session 带sessionid
  $httpProvider.defaults.withCredentials = true
  delete $httpProvider.defaults.headers.common['X-Requested-With']

  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'templates/tabs.html'
  })

  // Each tab has its own nav history stack:

  .state('tab.notifications', {
    url: '/notifications',
    views: {
      'tab-notifications': {
        templateUrl: 'templates/tab-notifications.html',
        controller: 'NotiCtrl'
      }
    }
  })

  .state('tab.vacations', {
      url: '/vacations',
      views: {
        'tab-vacations': {
          templateUrl: 'templates/tab-vacations.html',
          controller: 'VacationsCtrl'

        }
      }
    })
    .state('tab.vacations.list', {
      url: '/list',
      templateUrl: 'templates/vacations/list.html',
      controller: 'VacationsListCtrl'
    })
    .state('tab.vacations.detail', {
      url: '/:id',
      templateUrl: 'templates/vacations/detail.html',
      controller: 'VacationsDetailCtrl'
    })
    .state('tab.vacations.add', {
      url: '/add',
      templateUrl: 'templates/vacations/add.html',
      controller: 'VacationsAddCtrl'
    })
    .state('tab.vacations.adddelaydetail', {
      url: '/:id/delay',
      templateUrl: 'templates/vacations/adddelaydetail.html',
      controller: 'VacationsAddDelayDetailCtrl'
    })
    .state('tab.vacations.delaydetail', {
      url: '/:id/delay/:delay_id',
      templateUrl: 'templates/vacations/delaydetail.html',
      controller: 'VacationsDelayDetailCtrl'
    })
    .state('tab.mine', {
      url: '/mine',
      views: {
        'tab-mine': {
          templateUrl: 'templates/tab-mine.html',
          controller: 'MineCtrl'
        }
      }
    })
    .state('tab.mine.dash', {
      url: '/dash',
      templateUrl: 'templates/mine/dash.html',
      controller: 'MineDashCtrl'
    })
    .state('tab.mine.info', {
      url: '/info',
      templateUrl: 'templates/mine/info.html',
      controller: 'MineInfoCtrl'
    })
    .state('tab.mine.evaluate', {
      url: '/evaluate',
      templateUrl: 'templates/mine/evaluate.html',
      controller: 'MineEvaluateCtrl'
    })
    .state('tab.mine.amount', {
      url: '/amount',
      templateUrl: 'templates/mine/amount.html',
      controller: 'MineAmountCtrl'
    })
    .state('tab.mine.mark', {
      url: '/mark',
      templateUrl: 'templates/mine/mark.html',
      controller: 'MineMarkCtrl'
    })


  .state('tab.judge', {
      url: '/judge',
      views: {
        'tab-judge': {
          templateUrl: 'templates/tab-judge.html',
        }
      }
    })
    .state('tab.judge.list', {
      url: '/list',
      templateUrl: 'templates/judge/list.html',
      controller: 'JudgeListCtrl'
    })
    .state('tab.judge.detail', {
      url: '/:id',
      templateUrl: 'templates/judge/detail.html',
      controller: 'JudgeDetailCtrl'
    })
    .state('tab.judge.delaydetail', {
      url: '/:id/delay/:delay_id',
      templateUrl: 'templates/judge/delaydetail.html',
      controller: 'JudgeDelayDetailCtrl'
    })
    .state('login', {
      url: '/login',
      templateUrl: 'templates/login.html',
      controller: 'LoginCtrl'
    })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/notifications')

  // 未登录跳转管理
  $httpProvider.interceptors.push(function($rootScope, $location, $q, Utils) {
    return {
      request: function(config) {
        // console.log(config)
        if (config.url.indexOf('.html') < 0 && config.method != 'OPTIONS') {

          if ($rootScope.loadCount == 0) {
            $rootScope.loading(true)
            $rootScope.loadCount += 1
          }
        }

        return config
      },
      response: function(response) {
        // console.log(angular.toJson(response))
        if (response.status == 404) {
          $rootScope.loading(false)
          $rootScope.loadCount = 0
        }
        if (response.config.url.indexOf('.html') >= 0 || response.config.method == 'OPTIONS') {
          return response
        }
        // console.log(response)

        // 联网loading
        $rootScope.loadCount -= 1
        if ($rootScope.loadCount <= 0) {
          $rootScope.loading(false)
          $rootScope.loadCount = 0
        }
	
				// 递归设置img属性的链接为服务器链接
          var setImg = function(arr) {
            for (var i in arr) {
              // console.log(i);
              if (typeof arr[i] == 'object') {
                setImg(arr[i]);
              } else {
                if (i.indexOf('img') >= 0 || i.indexOf('Img') >= 0) {
                  if (arr[i]) {
                    // 不为空时才设置
                    if (arr[i].indexOf(server) < 0) {
                      // 判断是否是绝对路径
                      arr[i] = baseUrl + '/file?imgurl=' + arr[i]
                    }
                  }
                }
              }
            }
          }

        if (!Utils.isResponseOk(response.data)) {
          if (response.data.state == 102) {
            $rootScope.toast('请登录')
            $location.path('/login')
          }
          $rootScope.toast(response.data.message)
        } else {
        	setImg(response.data)
        }


					

        if (Utils.debug) {
          console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
          console.log(response.config.method + ' : ' + response.config.url)
          console.log(angular.toJson(response.data))
          console.log(response.data)
          console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        }


        return response
      },
      responseError: function(rejection) {
        // console.log(angular.toJson(rejection))
        $rootScope.loading(false)
        $rootScope.loadCount = 0
        if (rejection.config.url.indexOf('.html') >= 0 || rejection.config.method == 'OPTIONS') {
          return rejection
        }
        $rootScope.toast('连接失败')
        $rootScope.loadCount = 0

        return $q.reject(rejection)
      }
    }
  })
})
